package config

import (
	"encoding/json"

	"infosec.com.cn/crypto-http/config/ntv"
)

// Request 包括 NTV 结构数组
type Request struct {
	needMarshal bool
	Data        []*ntv.NTV `json:"Data,omitempty"`
}

func NewRequestWithoutMarshal() *Request {
	return &Request{
		needMarshal: false,
		Data:        make([]*ntv.NTV, 0),
	}
}

func NewRequest() *Request {
	return &Request{
		needMarshal: true,
		Data:        make([]*ntv.NTV, 0),
	}
}

// append 拼接多个 ntv.NTV, 返回当前位置
func (cr *Request) Append(data *ntv.NTV) int {
	cr.Data = append(cr.Data, data)
	return len(cr.Data) - 1
}

func (cr *Request) Marshal() ([]byte, error) {
	if cr.needMarshal {
		for _, data := range cr.Data {
			data.Marshal()
		}
	}
	return json.Marshal(cr)
}

func (cr *Request) MarshalIndent(prefix, indent string) ([]byte, error) {
	if cr.needMarshal {
		for _, data := range cr.Data {
			data.Marshal()
		}
	}
	return json.MarshalIndent(cr, prefix, indent)
}
